package com.qqtech.qquan.circle.controller;

import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.BizzLevel1Enum;
import com.qqtech.core.common.enums.BizzLevel2Enum;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.activity.enums.ActivityBaseCostTypeDictEnum;
import com.qqtech.qquan.activity.enums.ActivityBaseTypeDictEnum;
import com.qqtech.qquan.activity.enums.ActivityConst;
import com.qqtech.qquan.activity.model.ActivityBaseQuery;
import com.qqtech.qquan.activity.model.ActivityBaseVo;
import com.qqtech.qquan.activity.service.ActivityBaseService;
import com.qqtech.qquan.activity.service.ActivitySysDictService;
import com.qqtech.qquan.circle.enums.CircleBaseStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleConst;
import com.qqtech.qquan.circle.enums.CircleTopicStatusDictEnum;
import com.qqtech.qquan.circle.model.CircleBase;
import com.qqtech.qquan.circle.model.CircleBaseVo;
import com.qqtech.qquan.circle.model.CircleMemberQuery;
import com.qqtech.qquan.circle.model.CircleMemberVo;
import com.qqtech.qquan.circle.model.CircleSysDict;
import com.qqtech.qquan.circle.model.CircleTopic;
import com.qqtech.qquan.circle.model.CircleTopicQuery;
import com.qqtech.qquan.circle.model.CircleTopicVo;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleMemberGradeService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.circle.service.CircleSysDictService;
import com.qqtech.qquan.circle.service.CircleTopicService;
import com.qqtech.qquan.pub.enums.PromotionTargetTypeEnumDictEnum;
import com.qqtech.qquan.pub.enums.PubPraiseStatusDictEnum;
import com.qqtech.qquan.pub.model.PubPraise;
import com.qqtech.qquan.pub.model.PubPraiseQuery;
import com.qqtech.qquan.pub.model.PubPraiseVo;
import com.qqtech.qquan.pub.model.PubPromotionVo;
import com.qqtech.qquan.pub.service.PubCommentService;
import com.qqtech.qquan.pub.service.PubConcernService;
import com.qqtech.qquan.pub.service.PubPraiseService;
import com.qqtech.qquan.pub.service.PubPromotionService;
import com.qqtech.qquan.push.service.PushLogService;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.user.enums.UserShieldTypeDictEnum;
import com.qqtech.qquan.user.model.UserBase;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserValue;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserShieldService;
import com.qqtech.qquan.user.service.UserValueService;
import com.qqtech.qquan.vote.model.VoteItemQuery;
import com.qqtech.qquan.vote.service.VoteItemService;
import com.qqtech.qquan.vote.service.VoteResultService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/circle/topic")
public class CircleTopicController extends BaseWebController<CircleTopic, CircleTopicQuery> {
	@Resource
	private PushLogService pushLogService;
	@Resource
	private CircleBaseService circleBaseService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private CircleMemberGradeService circleMemberGradeService;
	@Resource
	private CircleTopicService circleTopicService;
	@Resource
	private UserBaseService userBaseService;

	@Resource
	private PubCommentService pubCommentService;

	@Resource
	private PubPraiseService pubPraiseService;

	@Resource
	private PubConcernService pubConcernService;

	@Resource
	private ActivityBaseService activityBaseService;
	
	@Resource
	private PubPromotionService pubPromotionService;

	@Resource
	private ActivitySysDictService activitySysDictService;
	
	@Resource
	private VoteItemService voteItemService;
	
	@Resource
	private VoteResultService voteResultService;
	
	@Resource
	private UserShieldService userShieldService;
	
	@Resource
	private CircleSysDictService circleSysDictService;
	
	@Resource
	private UserValueService userValueService;

	@Override
	protected BaseService<CircleTopic> getBaseService() {
		return circleTopicService;
	}

	/**
	 * 话题详情
	 * 
	 * @param circleTopicQuery
	 * @return
	 */
	@RequestMapping(value = "/detail")
	@ResponseBody
	public Result detail(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		Integer topicId = topicQuery.getId();
		if (topicId == null || topicId == 0) {
			result.addErr("话题id为空！");
			return result;
		}
		CircleTopicVo circleTopic = circleTopicService.getById(topicId);
		if (circleTopic == null) {
			result.addErr("找不到该话题！");
			return result;
		} else if (circleTopic.getStatus() != CircleTopicStatusDictEnum.NORMAL.getCode()) {
			result.addErr("该话题已不存在！");
			return result;
		}
		circleTopicService.increasePv(topicId);// 增加点击数
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		userVo = userBaseService.getById(circleTopic.getCreatorId());
		if(userVo!=null){
			circleTopic.setCreatorImg(userVo.getLogo());
			circleTopic.setCreatorName(userVo.getNick());
		}else{
			circleTopic.setCreatorName("未知用户");
		}
		addConcernInfo(circleTopic);
		addPraiseUserList(circleTopic);
		if(circleTopic.getPraiseUserList().length()>0){
			circleTopic.setIsShowPraiseList(true);// 详情页显示点赞人列表
		}else{
			circleTopic.setIsShowPraiseList(false);// 详情页显示点赞人列表
		}
		circleTopic.setImgString(circleTopic.getImg(),SysConst.IMG_POSTFIX);//话题图片
		if(!super.isVisitor()){
			if (pubPraiseService.isPraisedByUser(topicId,BizzLevel2Enum.CIRCLE_TOPIC.getCode(),super.getUserId())) {
				circleTopic.setIsPraised(YesNoEnum.YES.getCode());
			}
		}
		result.put("circleTopic", circleTopic);
		Integer voteHeight=-1;
		if(circleTopic.getIsVote()){
			VoteItemQuery voteItemQuery=new VoteItemQuery();
			voteItemQuery.setVoteId(circleTopic.getBizzId());
			int voteItemCount = voteItemService.queryCount(voteItemQuery);
			voteHeight=voteItemCount*130;
			if (null != super.getUserId()) {
				boolean isResult = voteResultService.isResult(voteItemQuery.getVoteId(), super.getUserId());
				if(!isResult){
					voteHeight=voteHeight+70;
				}
			}
			
		}
		result.put("voteHeight",voteHeight);
		
		if(!super.isVisitor()){
			Integer curUserId = super.getUserId();
			boolean canDeleteTopic = false;
			if(curUserId == circleTopic.getCreatorId()){
				canDeleteTopic = true;
			}else if(circleBaseService.isCircleCreator(curUserId, circleTopic.getCircleId())){
				canDeleteTopic = true;
			}else if(circleMemberService.isCircleManager(curUserId, circleTopic.getCircleId())){
				canDeleteTopic = true;
			}else{
				canDeleteTopic = false;
			}
			result.put("canDeleteTopic",canDeleteTopic);
		}
		return result;
	}

	/**
	 * 话题列表
	 * @param topicQuery
	 * @return
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	public Result list(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		topicQuery.setStatus(CircleBaseStatusDictEnum.NORMAL.getCode());
		topicQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(topicQuery.getPage(),new PageOrder(Direction.DESC, "id"));
		Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
		List<CircleTopicVo> topicList = topicPage.getContent();
		if (topicList != null && topicList.size() > 0) {
			for (CircleTopicVo topicVo : topicList) {
				userVo = userBaseService.getById(topicVo.getCreatorId());
				topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);
				topicVo.setCreatorImg(userVo.getLogo());
				topicVo.setCreatorName(userVo.getNick());
			}
		}
		result.put("topicPage", topicPage);
		return result;
	}

	private Result getActivity(Result result, CircleBase circleBase) {
		ActivityBaseQuery activityBaseQuery = new ActivityBaseQuery();
		activityBaseQuery.setType(ActivityBaseTypeDictEnum.CIRCLE.getCode());
		activityBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		activityBaseQuery.setBizzId(circleBase.getId());
		activityBaseQuery.setSearchEndAt(TimeUtil.now());
		Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.ASC, "status"),new PageOrder(Direction.DESC, "id"));
		List<ActivityBaseVo> list = activityBaseService.queryList(activityBaseQuery, pageKit);
		if (null != list && list.size() > 0) {
			ActivityBaseVo activityBaseVo = list.get(0);
			if (activityBaseVo.getCostType() == ActivityBaseCostTypeDictEnum.ONLINE.getCode()) {// 在线交易
				activityBaseVo.setShowCost("￥" + activityBaseVo.getCost());
			} else {
				String typeName = activitySysDictService.dictValue(ActivityConst.DICTYPE_ACTIVITY_BASE_COSTTYPE,
						String.valueOf(activityBaseVo.getCostType()));
				activityBaseVo.setShowCost(typeName);
			}
			String statusName = activitySysDictService.dictValue(ActivityConst.DICTYPE_ACTIVITY_BASE_STATUS,
					String.valueOf(activityBaseVo.getStatus()));
			activityBaseVo.setShowStatus(statusName);
			activityBaseVo.setIsShowPraiseList(false);
			activityBaseVo.setSponsorName(circleBase.getName());
			addCommentAndPraiseInfo(activityBaseVo);
			result.put("activityBaseVo", activityBaseVo);
		}
		return result;
	}
	
	/**
	 * 查询几个圈子中最新的活动
	 * @param result
	 * @param circleId
	 * @return
	 */
	private Result getNewActivity4Circles(Result result, List<Integer> circleIds) {
		ActivityBaseQuery activityBaseQuery = new ActivityBaseQuery();
		activityBaseQuery.setType(ActivityBaseTypeDictEnum.CIRCLE.getCode());
		activityBaseQuery.setIsShow(YesNoEnum.YES.getCode());
		if(circleIds !=null && !circleIds.isEmpty()){
			activityBaseQuery.setIncludeBizzIds(circleIds);
		}
		activityBaseQuery.setSearchEndAt(TimeUtil.now());
		Pageable pageKit = new PageKit(1, 1, new PageOrder(Direction.ASC, "status"),new PageOrder(Direction.DESC, "id"));
		List<ActivityBaseVo> list = activityBaseService.queryList(activityBaseQuery, pageKit);
		if (null != list && list.size() > 0) {
			ActivityBaseVo activityBaseVo = list.get(0);
			CircleBase circleBase=circleBaseService.getById(activityBaseVo.getBizzId());
			if (activityBaseVo.getCostType() == ActivityBaseCostTypeDictEnum.ONLINE.getCode()) {// 在线交易
				activityBaseVo.setShowCost("￥" + activityBaseVo.getCost());
			} else {
				String typeName = activitySysDictService.dictValue(ActivityConst.DICTYPE_ACTIVITY_BASE_COSTTYPE,
						String.valueOf(activityBaseVo.getCostType()));
				activityBaseVo.setShowCost(typeName);
			}
			String statusName = activitySysDictService.dictValue(ActivityConst.DICTYPE_ACTIVITY_BASE_STATUS,
					String.valueOf(activityBaseVo.getStatus()));
			activityBaseVo.setShowStatus(statusName);
			activityBaseVo.setIsShowPraiseList(false);
			activityBaseVo.setSponsorName(circleBase.getName());
			addCommentAndPraiseInfo(activityBaseVo);
			result.put("activityBaseVo", activityBaseVo);
		}
		return result;
	}

	// 评论、点赞数据
	private void addCommentAndPraiseInfo(ActivityBaseVo vo) {
		Integer commentCount = pubCommentService.getCommentCountByBizz(vo.getId(), BizzLevel1Enum.ACTIVITY.getCode());
		vo.setReplyCount(commentCount);
		vo.setIsPraised(YesNoEnum.NO.getCode());
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(vo.getId(),
				BizzLevel1Enum.ACTIVITY.getCode());
		if (praiseList != null && praiseList.size() > 0) {
			vo.setPraiseCount(praiseList.size());
			for (PubPraise pp : praiseList) {
				if (pp.getCreatorId().equals(super.getUserId())) {
					vo.setIsPraised(YesNoEnum.YES.getCode());
					break;
				}
			}
		} else {
			vo.setPraiseCount(0);
		}
	}

	/**
	 * 分页查询一个圈子的话题
	 * @param topicQuery【必须有circleId属性并赋值】
	 * @return
	 */
	@RequestMapping(value = "/list4circle")
	@ResponseBody
	public Result list4circle(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		Integer circleId = topicQuery.getCircleId();
		if (circleId == null) {
			result.addErr("圈子信息为空！");
			return result;
		}
		CircleBase circleBase = circleBaseService.getById(circleId);
		if(circleBase==null){
			result.addErr("找不到该圈子！");
			return result;
		}
		if(topicQuery.getPage() ==1){
			topicQuery.setIsShow(YesNoEnum.YES.getCode());
			topicQuery.setIsTop(YesNoEnum.YES.getCode());//已置顶
			Pageable pageKit2 = new PageKit(1,Integer.MAX_VALUE, new PageOrder(Direction.DESC, "topAt"));
			List<CircleTopicVo> topicList4Top = circleTopicService.queryList(topicQuery, pageKit2);
			result.put("topicList4Top", topicList4Top);//置顶话题			
		}
		Integer isShowMemberGrade = circleBase.getIsShowMemberGrade();
		boolean isShowMemberGradeB = isShowMemberGrade == YesNoEnum.YES.getCode() ? true:false;
		
		List<Integer> myPraiseTopicIds = Lists.newArrayList();
		if(!super.isVisitor()){//屏蔽
			List<Integer> shieldUserIds=userShieldService.getShieldUserIds(super.getUserId(), UserShieldTypeDictEnum.CIRCLE_TOPIC);
			if(null!=shieldUserIds&&shieldUserIds.size()>0){
				topicQuery.setFilterUserIds(shieldUserIds);
			}
			myPraiseTopicIds= getUserPraisedTopicIds(super.getUserId());
		}
		topicQuery.setIsShow(YesNoEnum.YES.getCode());
		topicQuery.setIsTop(YesNoEnum.NO.getCode());//未置顶
		Pageable pageKit = new PageKit(topicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
		List<CircleTopicVo> topicList = topicPage.getContent();
		
		CircleMemberVo memberVo = null;// 用于取用户呢称、头像
		if (topicList != null && topicList.size() > 0) {
			//hashMap--存放圈子成员完整信息
			LinkedHashMap<Integer, CircleMemberVo> memberMap = circleMemberService.getCircleTopicCreatorsMap(circleId);
			for (CircleTopicVo topicVo : topicList) {
				memberVo = memberMap.get(topicVo.getCreatorId());
				if(memberVo!=null){
					topicVo.setCreatorName(memberVo.getMemberName());
					topicVo.setCreatorImg(memberVo.getMemberImg());
					if(isShowMemberGradeB){
						topicVo.setCreatorGradeName(memberVo.getGradeName());
					}else{
						topicVo.setCreatorGradeName("");
					}
				}else{
					topicVo.setCreatorName("未知用户");
				}
				topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);//封装图片集合
				if(!myPraiseTopicIds.isEmpty()){
					if(myPraiseTopicIds.contains(topicVo.getId())){
						topicVo.setIsPraised(YesNoEnum.YES.getCode());
					}
				}
			}
		}
		result.put("circleId", circleId);
		result.put("topicPage", topicPage);
		if(topicQuery.getPage() ==1){
			result = getActivity(result, circleBase);
			boolean isPromotion=pubPromotionService.isTargetPromotion(circleId, PromotionTargetTypeEnumDictEnum.CIRCLE.getCode());
			List<PubPromotionVo> promotionList = pubPromotionService.getPubPromotionVoByTarget(circleId, PromotionTargetTypeEnumDictEnum.CIRCLE.getCode());
			result.put("promotionList", promotionList);
			result.put("isPromotion", isPromotion);
		}
		return result;
	}
	
	/**
	 * 分页查询一个圈子的话题
	 * 管理圈子的话题（专用）
	 * @param topicQuery【必须有circleId属性并赋值】
	 * @return
	 */
	@RequestMapping(value = "/list4manageCircle")
	@ResponseBody
	public Result list4manageCircle(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		Integer circleId = topicQuery.getCircleId();
		if (circleId == null) {
			result.addErr("圈子信息为空！");
			return result;
		}
		Pageable pageKit = new PageKit(topicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
		List<CircleTopicVo> topicList = topicPage.getContent();
		CircleMemberVo memberVo = null;// 用于取用户呢称、头像
		if (topicList != null && topicList.size() > 0) {
			//hashMap--存放圈子成员完整信息
			LinkedHashMap<Integer, CircleMemberVo> memberMap = circleMemberService.getCircleTopicCreatorsMap(circleId);
			for (CircleTopicVo topicVo : topicList) {
				memberVo = memberMap.get(topicVo.getCreatorId());
				if(memberVo!=null){
					topicVo.setCreatorName(memberVo.getMemberName());
					topicVo.setCreatorImg(memberVo.getMemberImg());
				}else{
					topicVo.setCreatorName("未知用户");
				}
				topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);//封装图片集合
			}
		}
		result.put("topicPage", topicPage);
		return result;
	}

	/**
	 * 我的话题列表
	 *
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myTopicList")
	@ResponseBody
	public Result myTopicList(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		CircleBaseVo circleVo = null;
		Integer curUserId = super.getUserId();// 当前用户id
		UserBaseVo curUser = userBaseService.getById(curUserId);
		String curUserLogo = curUser.getLogo();
		String curUserName = curUser.getNick();
		topicQuery.setCreatorId(curUserId);// 版主

		Pageable pageKit = new PageKit(topicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
		List<CircleTopicVo> topicList = topicPage.getContent();
		if (topicList != null && topicList.size() > 0) {
			LinkedHashMap<Integer, CircleBaseVo> circleMap = getCirlcesMapByTopicList(topicList);
			for (CircleTopicVo topicVo : topicList) {
				topicVo.setCreatorImg(curUserLogo);
				topicVo.setCreatorName(curUserName);
				topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);
				circleVo = circleMap.get(topicVo.getCircleId());
				if(circleVo!=null){
					topicVo.setCircleName(circleVo.getName());
				}else{
					topicVo.setCircleName("");
				}
			}
		}
		result.put("topicPage", topicPage);
		return result;
	}

	/**
	 * 创建一个话题
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/create")
	@ResponseBody
	public Result create(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer curUserId = super.getUserId();// 当前用户id
		topic.setCreatorId(curUserId);
		Integer circleId = topic.getCircleId();
		CircleBaseVo circleBaseVo = circleBaseService.getById(circleId);
		if(circleBaseVo.isGroupChat()){
			result.addErr("该圈子没有开放话题功能！");
			return result;
		}
		CircleMemberVo member = circleMemberService.getCircleMember(curUserId,circleId);
		if(member==null){
			result.addErr("您不是这个圈子的成员！");
			return result;
		}
		if(member.isBlack()){
			result.addErr("您已经被圈主或管理员屏蔽！");
			return result;
		}
		if (validateCircleTopic(topic, result, true)) {
			circleTopicService.addTopic(topic);
		}
		return result;
	}

	/**
	 * 修改一个话题
	 * 
	 * @param topicNew
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/update")
	@ResponseBody
	public Result update(@RequestBody CircleTopic topicNew) {
		Result result = new Result();

		if (validateCircleTopic(topicNew, result, false)) {
			Integer topicId = topicNew.getId();
			CircleTopic topicDB = circleTopicService.getById(topicId);
			if (topicDB == null) {
				result.addErr("话题不存在");
				return result;
			}
			Integer curUserId = super.getUserId();// 当前用户id
			if (!curUserId.equals(topicDB.getCreatorId())) {
				result.addErr("您不是版主,不能修改此话题");
				return result;
			}

			CircleTopic updateTopic = new CircleTopic();
			updateTopic.setId(topicId);
			updateTopic.setImg(topicNew.getImg());
			// 值首尾trim
			String content = topicNew.getContent();
			if (StringUtils.isNotBlank(content)) {
				content = content.trim();
			}
			updateTopic.setContent(content);
			circleTopicService.updateById(updateTopic);
		}
		return result;
	}

	/**
	 * 删除一个话题
	 * @param topicNew
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Result delete(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer topicId = topic.getId();
		CircleTopic topicDB = circleTopicService.getById(topicId);
		if (topicDB == null) {
			result.addErr("话题不存在");
			return result;
		}
		Integer circleId = topicDB.getCircleId();
		Integer curUserId = super.getUserId();// 当前用户id
		CircleMemberVo member = circleMemberService.getCircleMember(curUserId,circleId);
		boolean canDoDelete = false;//是否有权限
		if(member != null){
			//圈主、管理员、版主 才有权限删除话题
			if (member.isCircleCreator()){
				canDoDelete = true;//圈主
			}else if(member.isCircleManager()){
				canDoDelete = true;//管理员
			}else if(circleTopicService.isTopicCreator(curUserId, topicId)){
				canDoDelete = true;//版主
			}
			if(canDoDelete){
				circleTopicService.deleteTopic(topicId,curUserId);
			}else{
				result.addErr("您没有权限删除此话题");
			}
		}else{
			result.addErr("您没有权限删除此话题");
		}
		return result;
	}

	/**
	 * 话题置顶
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/doTop4Topic")
	@ResponseBody
	public Result doTop4Topic(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer topicId = topic.getId();
		Integer curUserId = super.getUserId();
		CircleTopic topicDB = circleTopicService.getById(topicId);
		if (topicDB == null) {
			result.addErr("话题不存在");
			return result;
		}
		circleTopicService.doTop4Topic(topicId,topic.getTag(),curUserId);
		return result;
	}

	/**
	 * 话题取消置顶
	 * 
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/undoTop4Topic")
	@ResponseBody
	public Result undoTop4Topic(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer topicId = topic.getId();
		Integer curUserId = super.getUserId();
		CircleTopic topicDB = circleTopicService.getById(topicId);
		if (topicDB == null) {
			result.addErr("话题不存在");
			return result;
		}
		circleTopicService.undoTop4Topic(topicId,curUserId);
		return result;
	}
	
	/**
	 * 屏蔽话题
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/hide")
	@ResponseBody
	public Result hide(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer topicId = topic.getId();
		CircleTopic topicDB = circleTopicService.getById(topicId);
		if (topicDB == null) {
			result.addErr("话题不存在");
			return result;
		}
		Integer curUserId = super.getUserId();//当前用户id
		Integer circleId = topicDB.getCircleId();
		CircleMemberVo member = circleMemberService.getCircleMember(curUserId,circleId);
		boolean canDoHide = false;//是否有权限
		if(member != null){
			//圈主、管理员、版主 才有权限--隐藏话题
			if (member.isCircleCreator()){
				canDoHide = true;//圈主
			}else if(member.isCircleManager()){
				canDoHide = true;//管理员
			}else if(circleTopicService.isTopicCreator(curUserId, topicId)){
				canDoHide = true;//版主
			}
			if(canDoHide){
				circleTopicService.hideTopic(topicId,curUserId);
			}else{
				result.addErr("无权操作！");
			}
		}else{
			result.addErr("无权操作！");
		}
		return result;
	}
	
	/**
	 * 取消屏蔽话题（显示）
	 * @param topic
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/show")
	@ResponseBody
	public Result show(@RequestBody CircleTopic topic) {
		Result result = new Result();
		Integer topicId = topic.getId();
		CircleTopic topicDB = circleTopicService.getById(topicId);
		if (topicDB == null) {
			result.addErr("话题不存在");
			return result;
		}
		Integer curUserId = super.getUserId();//当前用户id
		Integer circleId = topicDB.getCircleId();
		CircleMemberVo member = circleMemberService.getCircleMember(curUserId,circleId);
		boolean canDoShow = false;//是否有权限
		if(member != null){
			//圈主、管理员、版主 才有权限--隐藏话题
			if (member.isCircleCreator()){
				canDoShow = true;//圈主
			}else if(member.isCircleManager()){
				canDoShow = true;//管理员
			}else if(circleTopicService.isTopicCreator(curUserId, topicId)){
				canDoShow = true;//版主
			}
			if(canDoShow){
				circleTopicService.showTopic(topicId,curUserId);
			}else{
				result.addErr("无权操作！");
			}
		}else{
			result.addErr("无权操作！");
		}
		return result;
	}

	/**
	 * 某个圈子的新增话题数量
	 * 用于圈子列表，未读数量小红点
	 * @param topicQuery
	 * @return
	 */
	@RequestMapping(value = "/newCount4Circle")
	@ResponseBody
	public Result newCount4Circle(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		Integer circleId = topicQuery.getCircleId();
		if (circleId == null) {
			result.put("newTopicCount", 0);
			return result;
		}
		Timestamp startAt = topicQuery.getStartAt();
		if(startAt==null){
			startAt = TimeUtil.now();
		}
		topicQuery.setIsShow(YesNoEnum.YES.getCode());
		topicQuery.setStatus(CircleTopicStatusDictEnum.NORMAL.getCode());
		if(!super.isVisitor()){
			List<Integer> filterUserIds = Lists.newArrayList();
			filterUserIds.add(super.getUserId());
			topicQuery.setFilterUserIds(filterUserIds);//不包括我自己发布的
		}
		int count4new = circleTopicService.queryCount(topicQuery);
		result.put("newTopicCount", count4new);
		result.put("circleId", circleId);
		return result;
	}
	
	/**
	 * 话题标签-列表
	 */
	@RequestMapping(value = "/tagList")
	@ResponseBody
	public Result tagList() {
		Result result = new Result();
		List<CircleSysDict> typeList = circleSysDictService.get(CircleConst.DICTYPE_CIRCLE_TOPIC_TAG);
		result.put("tagList", typeList);
		return result;
	}
	
	/**
	 * 查询一个话题的点赞人列表
	 * @param topicQuery
	 * @return
	 */
	@RequestMapping(value = "/getPraiseUserList")
	@ResponseBody
	public Result getPraiseUserList(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(topicQuery.getId(),BizzLevel2Enum.CIRCLE_TOPIC.getCode());
		List<UserBase> userList4Praise = Lists.newArrayList();
		StringBuffer sb=new StringBuffer();
		if(praiseList!=null && praiseList.size()>0){
			for (int i = 0; i < praiseList.size(); i++) {
				PubPraise praise = praiseList.get(i);
				UserBase user = userBaseService.getById(praise.getCreatorId());
				if(user !=null){
					userList4Praise.add(user);
					if (i == praiseList.size() - 1) {
						sb.append("<a href='#' style='text-decoration: none' id='");
						sb.append(user.getId());
						sb.append("'>");
						sb.append(user.getNick());
						sb.append("</a>");
					} else {
						sb.append("<a href='#'  style='text-decoration: none' id='");
						sb.append(user.getId());
						sb.append("'>");
						sb.append(user.getNick());
						sb.append("</a>");
						sb.append("，");
					}
				}
			}
		}
		result.put("praiseUserList",sb.toString());
		result.put("userList4Praise", userList4Praise);
		return result;
	}
	
	/**
	 * 社区主页--分页查询我加入的圈子的动态
	 * @param topicQuery【可传入社区id来过滤社区】
	 * @return
	 */
	@RequestMapping(value = "/listCicleTopic4Community")
	@ResponseBody
	public Result listCicleTopic4Community(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		if(super.isVisitor()){
			return result;
		}
		Integer curUserId = super.getUserId();
		CircleMemberQuery query=new CircleMemberQuery();
		query.setMemberId(curUserId);
		query.setCommunityId(topicQuery.getCommunityId());
		List<Integer> myCircleIds = circleMemberService.queryMyCircleIds(query);//我的圈子id列表
		if(!myCircleIds.isEmpty()){
			topicQuery.setCircleIds(myCircleIds);
			//加入【屏蔽人过滤】
			List<Integer> shieldUserIds=userShieldService.getShieldUserIds(curUserId, UserShieldTypeDictEnum.CIRCLE_TOPIC);
			if(null!=shieldUserIds&&shieldUserIds.size()>0){
				topicQuery.setFilterUserIds(shieldUserIds);
			}
			topicQuery.setIsShow(YesNoEnum.YES.getCode());
			Pageable pageKit = new PageKit(topicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
			Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
			List<CircleTopicVo> topicList = topicPage.getContent();
			
			UserBaseVo creatorVo = null;// 用于取用户呢称、头像
			CircleBaseVo circleBaseVo=null;
			UserValue userValue = null;// 用于取用户等级
			if (topicList != null && topicList.size() > 0) {
				//hashMap--存放话题发布人的完整信息
				LinkedHashMap<Integer, UserBaseVo> memberMap = getCreatorsMap4TopicList(topicList);
				for (CircleTopicVo topicVo : topicList) {
					creatorVo = memberMap.get(topicVo.getCreatorId());
					userValue = userValueService.getById(topicVo.getCreatorId());
					topicVo.setHonorLevel(userValue.getHonorLevel());
					topicVo.setHonorLevelName(userValue.getHonorLevelName());
					if(creatorVo!=null){
						topicVo.setCreatorName(creatorVo.getNick());
						topicVo.setCreatorImg(creatorVo.getLogo());
					}else{
						topicVo.setCreatorName("未知用户");
					}
					circleBaseVo=circleBaseService.getById(topicVo.getCircleId());
					topicVo.setCircleName(circleBaseVo.getName());
					topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);//封装图片集合
					topicVo.setIsPraised(YesNoEnum.NO.getCode());
					if(null!=super.getUserId()){
						if (pubPraiseService.isPraisedByUser(topicVo.getId(),BizzLevel2Enum.CIRCLE_TOPIC.getCode(),super.getUserId())) {
							topicVo.setIsPraised(YesNoEnum.YES.getCode());
						}
					}
				}
			}
			result.put("topicPage", topicPage);
			if(topicQuery.getPage() ==1){
				result = getNewActivity4Circles(result,myCircleIds);//查询几个圈子中最新的一个活动
			}
		}
		return result;
	}
	
	
	/**
	 * 检查一个话题的属性是否为空
	 * 
	 * @param topic
	 * @param ret
	 * @param addMethod
	 * @return
	 */
	private boolean validateCircleTopic(CircleTopic topic, Result ret, boolean isAdd) {
		if (isAdd == false && topic.getId() == null) {
			ret.addErr("话题id为空！");
		}
		if (topic.getCircleId() == null) {
			ret.addErr("请选择圈子");
		}
		if (isAdd && StringUtils.isBlank(topic.getContent()) && StringUtils.isBlank(topic.getImg())) {
			ret.addErr("请填写话题内容或添加图片");
		}
		return ret.checkForm();
	}

	// 为话题-附加 关注信息
	private void addConcernInfo(CircleTopicVo topicVo) {
		if(!super.isVisitor()){
			Integer curUserId = super.getUserId();
			boolean isPraised = pubConcernService.isConcernedByUser(topicVo.getId(), BizzLevel2Enum.CIRCLE_TOPIC.getCode(), curUserId);
			if (isPraised) {
				topicVo.setIsConcern(YesNoEnum.YES.getCode());
			} else {
				topicVo.setIsConcern(YesNoEnum.NO.getCode());
			}
		}else{
			topicVo.setIsConcern(YesNoEnum.NO.getCode());
		}
	}

	// 为话题-附加点赞人列表
	private void addPraiseUserList(CircleTopicVo topicVo) {
		List<PubPraise> praiseList = pubPraiseService.queryPraiseListByBizz(topicVo.getId(),
				BizzLevel2Enum.CIRCLE_TOPIC.getCode());
		StringBuffer sb=new StringBuffer();
		List<UserBase> userList4Praise = Lists.newArrayList();
		if(praiseList!=null && praiseList.size()>0){
			for (int i = 0; i < praiseList.size(); i++) {
				PubPraise praise = praiseList.get(i);
				UserBase user = userBaseService.getById(praise.getCreatorId());
				if(user !=null){
					userList4Praise.add(user);
					if (i == praiseList.size() - 1) {
						sb.append("<a href='#' style='text-decoration: none' id='");
						sb.append(user.getId());
						sb.append("'>");
						sb.append(user.getNick());
						sb.append("</a>");
					} else {
						sb.append("<a href='#'  style='text-decoration: none' id='");
						sb.append(user.getId());
						sb.append("'>");
						sb.append(user.getNick());
						sb.append("</a>");
						sb.append("，");
					}
				}
			}
		}
		topicVo.setUserList4Praise(userList4Praise);//点赞人对象列表
		topicVo.setPraiseUserList(sb.toString());//点赞人列表string
	}

	/**
	 * 查询用户点赞过的话题ID列表
	 * @param userId
	 * @return
	 */
	private List<Integer> getUserPraisedTopicIds(Integer userId){
		List<Integer> topicIds = Lists.newArrayList();
		PubPraiseQuery praiseQ = new PubPraiseQuery();
		praiseQ.setBizzType(BizzLevel2Enum.CIRCLE_TOPIC.getCode());
		praiseQ.setCreatorId(userId);
		praiseQ.setStatus(PubPraiseStatusDictEnum.NORMAL.getCode());
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "bizzId")); 
		List<PubPraiseVo> praiseList = pubPraiseService.queryList(praiseQ, pageKit);
		if(praiseList!=null && praiseList.size()>0){
			for(PubPraiseVo praise : praiseList){
				if(!topicIds.contains(praise.getBizzId())){
					topicIds.add(praise.getBizzId());
				}
			}
		}
		return topicIds;
	}
	
	/**
	 * 查询话题发布人map
	 * @param topicList
	 * @return
	 */
	private LinkedHashMap<Integer, UserBaseVo> getCreatorsMap4TopicList(List<CircleTopicVo> topicList) {
		LinkedHashMap<Integer, UserBaseVo> map = new LinkedHashMap<Integer, UserBaseVo>();
		List<Integer> creatorIds = Lists.newArrayList();
		if(topicList !=null && topicList.size()>0){
			for(CircleTopicVo topic : topicList){
				creatorIds.add(topic.getCreatorId());
			}
		}
		if(creatorIds !=null && creatorIds.size()>0){
			map = userBaseService.queryUserMapListByUserIds(creatorIds);
		}
		return map;
	}
	
	
	/**
	 * 把圈子列表组装成map
	 * @param circleList
	 * @return
	 */
	private LinkedHashMap<Integer, CircleBaseVo> getCirlcesMapByList(List<CircleBaseVo> circleList) {
		LinkedHashMap<Integer, CircleBaseVo> map = new LinkedHashMap<Integer, CircleBaseVo>();
		if(circleList !=null && circleList.size()>0){
			for(CircleBaseVo circle : circleList){
				map.put(circle.getId(), circle);
			}
		}
		return map;
	}
	
	/**
	 * 把圈子列表组装成map
	 * @param circleList
	 * @return
	 */
	private LinkedHashMap<Integer, CircleBaseVo> getCirlcesMapByTopicList(List<CircleTopicVo> topicList) {
		LinkedHashMap<Integer, CircleBaseVo> map = new LinkedHashMap<Integer, CircleBaseVo>();
		List<Integer> circleIds = Lists.newArrayList();
		if(topicList !=null && topicList.size()>0){
			for(CircleTopicVo topic : topicList){
				circleIds.add(topic.getCircleId());
			}
		}
		if(circleIds !=null && circleIds.size()>0){
			List<CircleBaseVo> circleList = circleBaseService.queryListByCircleIds(circleIds);
			map = getCirlcesMapByList(circleList);
		}
		return map;
	}
	
	/**
	 *个人中心--分页查询他发布的圈子的动态
	 * @param topicQuery【creatorId】
	 * @return
	 */
	@RequestMapping(value = "/listTopic4Her")
	@ResponseBody
	public Result listTopic4Her(@RequestBody CircleTopicQuery topicQuery) {
		Result result = new Result();
		Integer creatorId = topicQuery.getCreatorId();
		if(creatorId==null){
			result.addErr("用户id为空");
			return result;
		}
		topicQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(topicQuery.getPage(), new PageOrder(Direction.DESC, "id"));
		Page<CircleTopicVo> topicPage = circleTopicService.queryPageList(topicQuery, pageKit);
		
		List<Integer> myPraiseTopicIds = Lists.newArrayList();
		if(!super.isVisitor()){//屏蔽
			myPraiseTopicIds= getUserPraisedTopicIds(super.getUserId());
		}
		
		List<CircleTopicVo> topicList = topicPage.getContent();
		if (topicList != null && topicList.size() > 0) {
			CircleMemberQuery query=new CircleMemberQuery();
			query.setMemberId(creatorId);
			List<Integer> herCircleIds = circleMemberService.queryMyCircleIds(query);
			List<CircleBaseVo> herCircles = Lists.newArrayList();
			if(!herCircleIds.isEmpty()){
				herCircles = circleBaseService.queryListByCircleIds(herCircleIds);
			}
			LinkedHashMap<Integer, CircleBaseVo> herCircleMap = getCirlcesMapByList(herCircles);
			CircleBaseVo circleTemp = null;//临时【圈子】
			UserBaseVo creatorVo = userBaseService.getById(creatorId);// 用于取用户呢称、头像
			for (CircleTopicVo topicVo : topicList) {
				if(creatorVo!=null){
					topicVo.setCreatorName(creatorVo.getNick());
					topicVo.setCreatorImg(creatorVo.getLogo());
				}else{
					topicVo.setCreatorName("未知用户");
				}
				circleTemp = herCircleMap.get(topicVo.getCircleId());
				if(circleTemp!=null){
					topicVo.setCircleName(circleTemp.getName());//圈子名称
				}
				topicVo.setImgString(topicVo.getImg(),SysConst.IMG_POSTFIX);//封装图片集合
				if(!myPraiseTopicIds.isEmpty()){
					if(myPraiseTopicIds.contains(topicVo.getId())){
						topicVo.setIsPraised(YesNoEnum.YES.getCode());
					}
				}
			}
		}
		result.put("topicPage", topicPage);
		return result;
	}
}
